﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AbstraX.Contracts;
using SolutionFramework.Entities;

namespace SolutionFramework.Service
{
    public class AbstraXCustomFields : ICustomFields
    {
        private SolutionFrameworkEntities entities;
        private string parentID;

        public AbstraXCustomFields(SolutionFrameworkEntities entities, string parentID)
        {
            // TODO: Complete member initialization
            this.entities = entities;
            this.parentID = parentID;
        }

        public string this[string name]
        {
            get
            {
                var customField = entities.AbstraXCustomFields.Where(p => p.ParentID == this.parentID && p.Name == name).Single();
                return customField.ID.ToString();
            }
            set
            {
                var customField = entities.AbstraXCustomFields.Where(p => p.ParentID == this.parentID && p.Name == name).SingleOrDefault();
                if (customField == null)
                {
                    var customObject = new AbstraXCustomField
                    {
                        ParentID = this.parentID,
                        Name = name,
                        FieldValue = value
                    };
                    entities.AbstraXCustomFields.AddObject(customObject);
                    entities.SaveChanges();
                }
                else
                {
                    customField.FieldValue = value;
                    entities.SaveChanges();
                }
            }
        }


    }
}
